package www.com.library.view;

import android.content.Context;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;

import www.com.library.util.DoubleConverter;

/**
 * 项目中价格显示控件
 */
public class PriceTextView extends TextView {
	private String mPrefix = null;
	private String mSubfix = null;

	private PriceSpannable mPriceSpan;
	private static final float MIN_ACCEPTABLE_TEXT_SIZE = 12;
	private static final float MIN_ACCEPTABLE_TEXT_WIDTH_DIFF = 2.0f;
	private float mExpectedTextSize;
	private float mTextScaleX;
	private boolean mIsAutoScaleText = false;
	private boolean mTextScaled = false;

	public PriceTextView(Context context) {
		super(context);
		init(context);
	}

	public PriceTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public PriceTextView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init(context);
	}

	private void init(Context context) {
		mPriceSpan = new PriceSpannable(context);
		mExpectedTextSize = getTextSize();
		final float textScaleX = getTextScaleX();
		if (textScaleX > 0)
			mTextScaleX = textScaleX;
	}

	/**
	 * 根据需要此处设置后缀文字的大小
	 * 
	 * @param context
	 * @param superSize
	 *            后缀文字的大小，R文件中的id值
	 */
	public void initPriceSpan(Context context, int superSize) {
		mPriceSpan = new PriceSpannable(context, superSize);
	}

	public void setAutoScaleText(boolean enable) {
		mIsAutoScaleText = enable;
	}

	/**
	 * 自定义文字大小
	 * 
	 * @param text
	 */
	public void rescaleText(CharSequence text) {
		if (!mIsAutoScaleText || mTextScaled)
			return;

		final TextPaint paint = getPaint();
		if (text != null && paint != null && mExpectedTextSize > 0) {
			/* Adjust scale to fit the rect */
			final float drawableW = getMeasuredWidth()
					- getCompoundPaddingLeft() - getCompoundPaddingRight();
			if (drawableW <= 0)
				return;

			final int textLen = text.length();
			float textSize = mExpectedTextSize - 11;
			float textScaleX = mTextScaleX;

			paint.setTextSize(textSize);
			paint.setTextScaleX(textScaleX);
			float width = paint.measureText(text, 0, textLen);
			if (width > drawableW) {
				float textStep = textSize / 2;
				float widthDiff = Math.abs(drawableW - width);
				while (widthDiff > MIN_ACCEPTABLE_TEXT_WIDTH_DIFF
						|| width > drawableW) {
					if (textSize < MIN_ACCEPTABLE_TEXT_SIZE)
						break;
					else if (width < drawableW && textStep < 1)
						break;
					else if (width > drawableW)
						textSize -= textStep;
					else if (width < drawableW)
						textSize += textStep;
					else
						break;

					if (textStep >= 1)
						textStep = textStep / 2;
					paint.setTextSize(textSize);
					width = paint.measureText(text, 0, textLen);
					widthDiff = Math.abs(drawableW - width);
				}

				float scaleXStep = 0.05f;
				while (width > drawableW) {
					textScaleX -= scaleXStep;
					if (textScaleX < 0.5f)
						break;
					paint.setTextScaleX(textScaleX);
					width = paint.measureText(text, 0, textLen);
				}

				setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
				setTextScaleX(textScaleX);
			} else {
				if (getTextSize() < mExpectedTextSize)
					setTextSize(TypedValue.COMPLEX_UNIT_PX, mExpectedTextSize);
				if (getTextScaleX() < mTextScaleX)
					setTextScaleX(mTextScaleX);
			}

			mTextScaled = true;
		}
	}

	public void setPrefix(String prefix) {
		mPrefix = prefix;
	}

	public String getPrefix() {
		return mPrefix;
	}

	public void setSubfix(String subfix) {
		mSubfix = subfix;
	}

	public String getSubfix() {
		return mSubfix;
	}

	/**
	 * 行情报价界面买卖价放大及显示逻辑
	 * @param price
	 * @param digits
	 */
	public void updateWithPrice(String price, int digits, int point, boolean isNormal) {
		SpannableStringBuilder builder = null;
		if (!isNormal) {
			if (price.length() > 1 && digits >= 0) {
				if ((price.length() - point) - (price.indexOf(".") + 1) > 1) {
					builder = mPriceSpan.createSpannableString(2, point, price);
				} else if ((price.length() - point) - (price.indexOf(".") + 1) == 1
						|| (price.length() - point) - (price.indexOf(".") + 1) == 0) {
					builder = mPriceSpan.createSpannableString(3, point, price);
				} else if((price.length() - point) - (price.indexOf(".") + 1) < 0 && point < price.length()){
					builder = mPriceSpan.createSpannableString(2, point, price);
				}else {//如果根据大点比率算出来的位置比价格长度还大，则不放大，跟ios做统一
					builder = mPriceSpan.createSpannableString(0, point, price);
				}
			} else {
				builder = mPriceSpan.createSpannableString(2, point, price);
			}
		} else {//游客登录不放大
			builder = mPriceSpan.createSpannableString(0, 0, price);
		}
		setText(builder);
	}

	/**
	 * 行情报价界面买卖价放大及显示逻辑
	 * @param price
	 */
	public void updateWithPrice(String price, String zoomRule, boolean isNormal) {
		SpannableStringBuilder builder = null;
		if (!isNormal && zoomRule.length() > 0 && zoomRule.contains("#")) {
			String strs[] = zoomRule.split("#");
            int startIndex = DoubleConverter.toIntData(strs[0]);
			int nums = DoubleConverter.toIntData(strs[1]);
			startIndex = price.length() - startIndex - 1;
			if(startIndex >= 0 && nums > 0){
				builder = mPriceSpan.createSpannableStrings(startIndex, nums, price);
				setText(builder);
			}else{
				setText(price);
			}
		} else {//游客登录不放大
			setText(price);
		}
	}

	@Override
	public void setText(CharSequence text, BufferType type) {
		mTextScaled = false;
		rescaleText(text);
		super.setText(text, type);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		rescaleText(getText());
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		mTextScaled = false;
		rescaleText(getText());
		super.onSizeChanged(w, h, oldw, oldh);
	}

}
